using System;
using System.Security.Cryptography;
using System.Text;

namespace FinDataAdmin.Tools
{
    class HashGenerator
    {
        static void Main(string[] args)
        {
            Console.WriteLine("FinData 哈希值生成器");
            Console.WriteLine("====================");
            
            // 生成监管者凭据的哈希值
            Console.WriteLine("\n监管者凭据哈希值:");
            Console.WriteLine($"用户名 'tjumis' 的SHA256哈希值: {ComputeSHA256Hash("tjumis")}");
            Console.WriteLine($"密码 '1895' 的SHA256哈希值: {ComputeSHA256Hash("1895")}");
            
            // 生成管理员凭据的哈希值和盐
            Console.WriteLine("\n管理员凭据哈希值:");
            string adminUsername = "admin1";
            string adminPassword = "admin123";
            var (hash, salt) = CreatePasswordHash(adminPassword);
            Console.WriteLine($"用户名: {adminUsername}");
            Console.WriteLine($"密码: {adminPassword}");
            Console.WriteLine($"哈希值: {hash}");
            Console.WriteLine($"盐值: {salt}");
            
            Console.WriteLine("\n将这些值添加到数据库中，即可使用相应的凭据登录。");
            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }
        
        // 计算SHA256哈希值
        static string ComputeSHA256Hash(string rawData)
        {
            using (SHA256 sha256Hash = SHA256.Create())
            {
                // 计算哈希值
                byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
                
                // 将字节数组转换为十六进制字符串
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }
        
        // 创建密码哈希和盐
        static (string hash, string salt) CreatePasswordHash(string password)
        {
            // 生成随机盐
            byte[] saltBytes = new byte[16];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(saltBytes);
            }
            string salt = Convert.ToBase64String(saltBytes);
            
            // 计算哈希
            string hash = ComputeHash(password, salt);
            
            return (hash, salt);
        }
        
        // 计算密码哈希
        static string ComputeHash(string password, string salt)
        {
            using (var sha256 = SHA256.Create())
            {
                // 将密码和盐组合
                string combined = password + salt;
                byte[] bytes = Encoding.UTF8.GetBytes(combined);
                
                // 计算哈希
                byte[] hashBytes = sha256.ComputeHash(bytes);
                
                // 转换为Base64字符串
                return Convert.ToBase64String(hashBytes);
            }
        }
    }
} 